package com.flying.arts.trade.domain.repository;

import com.flying.arts.common.domain.entity.Entity;
import com.flying.arts.trade.domain.entity.MatchedTrade;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository("matchedTradeRepository")
public class InMemoryMatchedTradeRepository implements MatchedTradeRepository {
    private Map<Long, MatchedTrade> matchedTrades;

    public InMemoryMatchedTradeRepository() {
        this.matchedTrades = new HashMap<>();
        MatchedTrade matchedTrade = null;
        matchedTrade = new MatchedTrade((long) 1, "恒生电子", 10000000, 42.38, 500, 42.38*500, 20170119,
                10000001, 44.00, 500, 44*500, 20170123, System.currentTimeMillis());
        matchedTrades.put((long) 1, matchedTrade);
    }

    @Override
    public void add(MatchedTrade entity) {
        matchedTrades.put(entity.getId(), entity);
    }

    @Override
    public void remove(Long id) {
        if (matchedTrades.containsKey(id)) matchedTrades.remove(id);
    }

    @Override
    public void update(MatchedTrade entity) {
        if (matchedTrades.containsKey(entity.getId())) matchedTrades.put(entity.getId(), entity);
    }

    @Override
    public boolean contains(Long id) {
        return matchedTrades.containsKey(id);
    }

    @Override
    public Entity get(Long id) {
        return matchedTrades.get(id);
    }

    @Override
    public Collection<MatchedTrade> findByStockName(String name) {
        Collection<MatchedTrade> trades = new ArrayList<>();
        int noOfChars = name.length();
        this.matchedTrades.forEach((k, v) -> {
            if (v.getStockName().toLowerCase().contains(name.subSequence(0, noOfChars))) {
                trades.add(v);
            }
        });
        return trades;
    }

    @Override
    public Collection<MatchedTrade> getAll() {
        return matchedTrades.values();
    }
}
